<template>
    <el-dialog :title="title" v-model="editFormVisible" @close="handleClose" width="1200px">
        <el-tabs v-model="activeName" @tab-click="handleClick" v-if="status === 2">
            <el-tab-pane label="异常任务处理" name="first">
                <el-form :model="formData" label-width="120px" :rules="formRules" ref="form">
                    <el-row gutter="20" class="mr-100">
                        <el-col :span="24">
                            <el-form-item label="异常编码" prop="TaskCode">
                                <el-input v-model="formData.TaskCode" disabled placeholder="自动生成" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row gutter="20" class="mr-100">
                        <el-col :span="12">
                            <el-form-item label="异常类型" prop="AbnormalTypeId">
                                <el-cascader v-model="formData.AbnormalTypeId" filterable :options="treeData"
                                    :disabled="addDisabled" :props="{ checkStrictly: true }" :key="cascaderKey"
                                    clearable placeholder="请选择异常类型" @change="cascaderChange" style="width: 100%;" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="优先级" prop="Priority">
                                <el-select v-model="formData.Priority" disabled placeholder="请选择优先级">
                                    <el-option v-for="item in priorityList" :key="item.key" :label="item.value"
                                        :value="item.key" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row gutter="20" v-if="formData.AbnormalTypeId.length > 0" class="mr-100">
                        <el-col :span="12">
                            <el-form-item label="负责人部门">
                                <el-cascader :options="deptList" v-model="abnormalType.depts" placeholder="未配置部门"
                                    :props="props1" disabled style="width: 100%;" clearable></el-cascader>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="负责人">
                                <el-select clearable v-model="abnormalType.persons" multiple placeholder="未配置部门负责人"
                                    disabled style="width: 100%">
                                    <el-option v-for="item in userList" :key="item.key" :label="item.value"
                                        :value="item.key" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row gutter="20" class="mr-100">
                        <el-col :span="24">
                            <el-form-item label="设备" prop="EquipmentCodes">
                                <el-select filterable clearable v-model="formData.EquipmentCodes"
                                    :disabled="addDisabled" multiple placeholder="请选择设备" style="width: 100%">
                                    <el-option v-for="item in BASE_MachineList" :key="item.key" :label="item.value"
                                        :value="item.key" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row gutter="20" class="mr-100">
                        <el-col :span="24">
                            <el-form-item label="异常附件" prop="InitiatorAttachments">
                                <el-upload action="#" :on-preview="handlePictureCardPreview" :on-remove="removePic"
                                    :http-request="uploadFile" multiple :limit="5" :disabled="addDisabled"
                                    :file-list="formData.InitiatorAttachments" style="width: 100%;">
                                    <el-button size="small" type="primary">点击上传</el-button>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row gutter="20" class="mr-100">
                        <el-col :span="24">
                            <el-form-item label="异常说明" prop="InitiatorRemarks">
                                <el-input v-model="formData.InitiatorRemarks" :disabled="addDisabled" type="textarea"
                                    placeholder="请输入发起备注" :rows="4" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row gutter="20" v-if="status != 0 && formData.Status != 0" class="mr-100">
                        <el-col :span="12">
                            <el-form-item label="发起人" prop="Initiator">
                                <el-select v-model="formData.Initiator" placeholder="发起人" style="width: 100%" disabled>
                                    <el-option v-for="item in userList" :key="item.key" :label="item.value"
                                        :value="item.key" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="formData.CurrentProcessor != null">
                            <el-form-item label="当前处理人" prop="CurrentProcessor">
                                <el-select v-model="formData.CurrentProcessor" placeholder="当前处理人" style="width: 100%"
                                    disabled>
                                    <el-option v-for="item in userList" :key="item.key" :label="item.value"
                                        :value="item.key" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <div v-if="status == 2">
                        <el-divider></el-divider>
                        <el-row gutter="20" class="mr-100">
                            <el-col :span="24">
                                <el-form-item label="处理附件" prop="TreatmentAttachments">
                                    <el-upload action="#" :on-preview="handlePictureCardPreview"
                                        :on-remove="removeTreatmentPic" :http-request="uploadTreatmentFile" multiple
                                        :limit="5" :disabled="cantOperationModel"
                                        :file-list="formData.TreatmentAttachments" style="width: 100%;">
                                        <el-button size="small" type="primary">点击上传</el-button>
                                    </el-upload>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row gutter="20" class="mr-100">
                            <el-col :span="24">
                                <el-form-item label="处理方法" prop="TreatmentMethod">
                                    <el-input v-model="formData.TreatmentMethod" :disabled="cantOperationModel"
                                        type="textarea" placeholder="请输入处理方法" :rows="4" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row gutter="20" class="mr-100">
                            <el-col :span="24">
                                <el-form-item label="处理结果" prop="TreatmentResult">
                                    <el-input v-model="formData.TreatmentResult" :disabled="cantOperationModel"
                                        placeholder="请输入处理结果" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="操作日志" name="second">
                <div class="timeline-container">
                    <el-timeline>
                        <el-timeline-item v-for="(activity, index) in logList" :key="index"
                            :timestamp="activity.CreateTime">
                            【{{ activity.OperationType }}】{{ activity.Operator }} <strong>{{ activity.Operation
                                }}</strong>
                            <br v-if="activity.Remarks !== ''"> <span style="color: gray;">&nbsp;&nbsp;{{
                                activity.Remarks != '' ? '意见：' + activity.Remarks : '' }}</span>
                        </el-timeline-item>
                    </el-timeline>
                </div>
            </el-tab-pane>
        </el-tabs>

        <!-- 新增时使用 -->
        <el-form :model="formData" label-width="120px" :rules="formRules" ref="form" v-else>
            <el-row gutter="20" class="mr-100">
                <el-col :span="24">
                    <el-form-item label="异常编码" prop="TaskCode">
                        <el-input v-model="formData.TaskCode" disabled placeholder="自动生成" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row gutter="20" class="mr-100">
                <el-col :span="12">
                    <el-form-item label="异常类型" prop="AbnormalTypeId">
                        <el-cascader v-model="formData.AbnormalTypeId" filterable :options="treeData"
                            :disabled="addDisabled" :props="{ checkStrictly: true }" :key="cascaderKey" clearable
                            placeholder="请选择异常类型" @change="cascaderChange" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="优先级" prop="Priority">
                        <el-select v-model="formData.Priority" placeholder="请选择优先级">
                            <el-option v-for="item in priorityList" :key="item.key" :label="item.value"
                                :value="item.key" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row gutter="20" v-if="formData.AbnormalTypeId?.length > 0" class="mr-100">
                <el-col :span="12">
                    <el-form-item label="负责人部门">
                        <el-cascader :options="deptList" v-model="abnormalType.depts" placeholder="未配置部门"
                            :props="props1" disabled style="width: 100%;" clearable></el-cascader>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="负责人">
                        <el-select clearable v-model="abnormalType.persons" multiple placeholder="未配置部门负责人" disabled
                            style="width: 100%">
                            <el-option v-for="item in userList" :key="item.key" :label="item.value" :value="item.key" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row gutter="20" class="mr-100">
                <el-col :span="24">
                    <el-form-item label="设备" prop="EquipmentCodes">
                        <el-select filterable clearable v-model="formData.EquipmentCodes" :disabled="addDisabled"
                            multiple placeholder="请选择设备" style="width: 100%">
                            <el-option v-for="item in BASE_MachineList" :key="item.key" :label="item.value"
                                :value="item.key" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row gutter="20" class="mr-100">
                <el-col :span="24">
                    <el-form-item label="异常附件" prop="InitiatorAttachments">
                        <el-upload action="#" :on-preview="handlePictureCardPreview" :on-remove="removePic"
                            :http-request="uploadFile" multiple :limit="5" :disabled="addDisabled"
                            :file-list="formData.InitiatorAttachments" style="width: 100%;">
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row gutter="20" class="mr-100">
                <el-col :span="24">
                    <el-form-item label="异常说明" prop="InitiatorRemarks">
                        <el-input v-model="formData.InitiatorRemarks" :disabled="addDisabled" type="textarea"
                            placeholder="请输入发起备注" :rows="4" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <!-- 弹框底部按钮 -->
        <template v-slot:footer>
            <div class="dialog-footer">
                <el-button @click="editFormVisible = false">取消</el-button>
                <el-button @click="returnVisible = true" v-if="isReturn">退回</el-button>
                <el-button @click="chooseUserVisible = true" v-if="isTrans">转派</el-button>
                <el-button type="primary" @click="submitForm('conform')" :loading="submitLoading"
                    v-if="formData.Status != 5 && !formData.IsRead">{{
                        submitbtnName }}</el-button>
            </div>
        </template>

        <!-- 图片预览弹框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
            <div class="image-container">
                <img :src="dialogImageUrl" alt="预览图片" class="responsive-image" />
            </div>
        </el-dialog>

        <!-- 转派弹框 -->
        <el-dialog v-model="chooseUserVisible" title="转派" width="500" align-center>
            <el-form-item label="转派人">
                <el-select v-model="chooseUser" filterable clearable placeholder="必选" style="width: 100%">
                    <el-option v-for="item in userList" :key="item.key" :label="item.value" :value="item.key" />
                </el-select>
            </el-form-item>
            <el-form-item label="转派原因">
                <el-input v-model="message" placeholder="请输入转派原因" />
            </el-form-item>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="chooseUserVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm('return')">
                        转派
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 退回弹框 -->
        <el-dialog v-model="returnVisible" title="退回" width="500" align-center>
            <el-form-item label="退回原因">
                <el-input v-model="message" placeholder="请输入退回原因" />
            </el-form-item>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="returnVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm('return')">
                        退回
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 确认弹框 -->
        <el-dialog v-model="conformVisible" title="确认" width="500" align-center>
            <el-form-item label="确认说明">
                <el-input v-model="conformMessage" placeholder="请输入确认说明" />
            </el-form-item>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="conformVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm('conform')">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </el-dialog>
</template>

<script>
import commonMixin from '@/views/_common/mixin'
import http from '@/../src/api/http.js'
const url = http.ipAddress
export default {
    mixins: [commonMixin],
    data() {
        return {
            abnormalType: {
                depts: [],
                persons: [],
            },
            props1: {
                // multiple: true,
                checkStrictly: true,
            },
            activeName: 'first',
            dialogTitle: '',//图片预览title
            isReturn: false,//退回按钮
            isTrans: false,//转派按钮
            returnVisible: false,//退回窗口
            message: null,//退回原因
            conformVisible: false,//确认窗口
            conformMessage: null,//确认原因
            chooseUserVisible: false,//转派窗口
            chooseUser: null,//转派人
            title: '',
            submitbtnName: '保存',
            addDisabled: false,//新增控件是否可用
            cantOperationModel: false,//查看模式
            cascaderKey: 1, // 初始 key 值
            status: 0,//0:新增，1修改，2操作
            dialogVisible: false,//展示图片
            dialogImageUrl: '',//图片地址
            editFormVisible: false, // 弹框显示状态
            submitLoading: false, // 提交加载状态
            formData: {
                TaskCode: '', // 异常编码
                AbnormalTypeId: [], // 异常类型（级联选择器绑定数组）
                Initiator: null, // 发起人
                Priority: null, // 优先级
                InitiatorRemarks: '', // 发起备注
                InitiatorAttachments: [],//发起人附件
                Status: null, // 状态
                IsRead: false,//是否仅阅读

                CurrentProcessor: null,//当前处理人
                TreatmentMethod: '',//处理方法
                TreatmentResult: '',//处理结果
                TreatmentAttachments: [],//处理附件
            },
            formRules: {},
            treeData: [], // 级联选择器数据
            deptList: [],
            userList: [],
            statusOptions: [],
            priorityList: [],//优先级
            BASE_MachineList: [],
            logList: [],//日志
        };
    },
    methods: {
        init() {
            this.abnormalType = {
                depts: [],
                persons: [],
            }
            this.activeName = 'first'
            this.dialogTitle = ''//图片预览title
            this.isReturn = false//退回按钮
            this.isTrans = false//转派按钮
            this.returnVisible = false//退回窗口
            this.message = null//退回原因
            this.chooseUserVisible = false//转派窗口
            this.conformVisible = false//确认窗口
            this.conformMessage = null//确认原因
            this.chooseUser = null//转派人
            this.title = ''
            this.submitbtnName = '保存'
            this.addDisabled = false//控制控件是否可用
            this.cantOperationModel = false//查看模式
            this.cascaderKey = 1 // 初始 key 值
            this.status = 0//0=新增，1修改，2操作
            this.dialogVisible = false//展示图片
            this.dialogImageUrl = ''//图片地址
            this.editFormVisible = false // 弹框显示状态
            this.submitLoading = false // 提交加载状态
            this.formRules = {
                AbnormalTypeId: [{ required: true, message: '请选择异常类型', trigger: 'change' }],
                Priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
                EquipmentCodes: [{ required: true, message: '请选择设备', trigger: 'blur' }],
                InitiatorRemarks: [{ required: true, message: '请输入异常说明', trigger: 'change' }],
                TreatmentMethod: [{ required: true, message: '请输入处理方法', trigger: 'change' }],
                TreatmentResult: [{ required: true, message: '请输入处理结果', trigger: 'change' }],
            }
            this.formData = {
                TaskCode: '', // 异常编码
                AbnormalTypeId: [], // 异常类型（级联选择器绑定数组）
                Initiator: null, // 发起人
                Priority: null, // 优先级
                InitiatorRemarks: '', // 发起备注
                InitiatorAttachments: [],//发起人附件
                Status: null, // 状态
                IsRead: false,//是否仅阅读

                CurrentProcessor: null,//当前处理人
                TreatmentMethod: '',//处理方法
                TreatmentResult: '',//处理结果
                TreatmentAttachments: [],//处理附件

            },
                this.logList = []
        },
        // 打开弹框
        openDialog(status, listData, data) {
            console.log('init', status, listData, data)
            this.init();
            if (!listData) {
                this.$message.error('详细页面初始化失败，字典为空');
                return;
            }
            this.deptList = this.transformData(listData.deptList)
            this.treeData = listData.treeData;
            this.BASE_MachineList = listData.BASE_MachineList
            this.userList = listData.userList;
            this.statusOptions = listData.statusOptions;
            this.priorityList = listData.priorityList;
            this.status = status;

            //如果是从编辑和查看来的（都是2）需要判断
            if (this.status == '2') {
                if (data.IsRead || data.Status == '0' || data.Status == '4' || data.Status == '5') {//查看模式、待确认、完成状态-->不可操作编辑
                    this.formRules = []
                    this.cantOperationModel = true
                } else {
                    this.cantOperationModel = false
                }
            }

            if (data) {
                // 编辑模式，填充表单数据
                this.formData = { ...data };
                // 恢复图片显示
                this.formData.InitiatorAttachments = this.stringToJson(this.formData.InitiatorAttachments)
                this.formData.InitiatorAttachments = this.addUrlPrefix(this.formData.InitiatorAttachments);
                this.formData.TreatmentAttachments = this.stringToJson(this.formData.TreatmentAttachments)
                this.formData.TreatmentAttachments = this.addUrlPrefix(this.formData.TreatmentAttachments);
                // 恢复成树状结构
                this.formData.AbnormalTypeId = this.findParentIds(this.treeData, this.formData.AbnormalTypeId);
                if (this.formData.AbnormalTypeId && this.formData.AbnormalTypeId.length > 0) {
                    this.cascaderChange(this.formData.AbnormalTypeId,this.formData.Priority)
                }
                
                this.formData.Status = this.formData.Status?.toString() || '0';
                this.refreshCascader();
                // 保存按钮的名称
                if (this.status == 2) {//转派
                    this.addDisabled = true
                    if (this.formData.Status == '0') {//发起
                        this.submitbtnName = '认领';
                    } else {
                        this.submitbtnName = '确认';
                    }
                    if (this.formData.Status != '5') {
                        if (this.formData.IsRead) {
                            this.title = '查看异常任务';
                        } else {
                            this.title = '处理异常任务';
                        }
                    } else {
                        this.title = '查看异常任务';
                    }
                } else {
                    this.addDisabled = false
                    this.submitbtnName = '保存';
                    this.title = '修改异常任务';
                }

                //修改标题
                var value = this.statusOptions.find((t) => t.key == this.formData.Status)
                let statusName = value ? value.value : status
                this.title += '(' + statusName + ')'
                this.getBtnShow()
                // title
                status == 0 ? '新增异常任务' : status == 1 ? '修改异常任务' : '处理异常任务';
            } else {
                this.title = '新增异常任务';
                this.isAdd = true;
                this.addDisabled = false
                // 新增模式，重置表单数据
                this.formData = {
                    TaskCode: '',
                    AbnormalTypeId: [],
                    Initiator: '',
                    InitiatorRemarks: '',
                    InitiatorAttachments: [],
                    Status: '0',
                };
            }
            this.editFormVisible = true;
        },
        getBtnShow() {
            this.isTrans = false
            this.isReturn = false
            //如果是阅读模式则仅阅读
            if (this.formData.IsRead) {
                return
            }
            if (this.formData.Status == '1') {//认领时可转派不可退回
                this.isTrans = true
                this.isReturn = false
            } else if (this.formData.Status == '2') {//转派时可退回不可转派
                this.isTrans = false
                this.isReturn = true
            } else if (this.formData.Status == '3') {//退回时可退回不可转派
                this.isTrans = true
                this.isReturn = false
            } else if (this.formData.Status == '4') {//待确认可退回不可转派
                this.isTrans = false
                this.isReturn = true
            }
        },
        //第一个按钮的操作动作
        getNextAction1() {
            if (this.formData.Status == '1') {
                return '2'
            }
            if (this.formData.Status == '2') {
                return '3'
            }
            if (this.formData.Status == '3') {
                return '2'
            }
            if (this.formData.Status == '4') {
                return '3'
            }
        },
        //第二个按钮的动作
        getNextAction2() {
            if (this.formData.Status == '0') {
                return '1'
            }
            if (this.formData.Status == '1') {
                return '4'
            }
            if (this.formData.Status == '2') {
                return '4'
            }
            if (this.formData.Status == '3') {
                return '4'
            }
            if (this.formData.Status == '4') {
                return '5'
            }
        },
        // 提交表单
        submitForm(btnAction) {
            var data = { ...this.formData }
            //判断下一动作
            if (btnAction == 'return') {
                data.Status = this.getNextAction1()
                if (data.Status == '2') {//转派
                    if (!this.chooseUser) {
                        this.$message.info('转派需要指定转派人')
                        return
                    }
                    data.Remarks = this.message
                    data.CurrentProcessor = this.chooseUser
                }
                if (data.Status == '3') {//退回
                    console.log(this.message)
                    if (!this.message?.trim()) {
                        this.$message.info('退回需要退回原因')
                        return
                    }
                    data.Remarks = this.message
                }
            } else {
                //确认时需要确认说明
                if (data.Status == '4') {
                    if (this.conformVisible == false) {
                        this.conformVisible = true
                        return
                    }
                    if (!this.conformMessage?.trim()) {
                        this.$message.info('退回需要退回原因')
                        return
                    } else {
                        data.Remarks = this.conformMessage
                    }
                }
                data.Status = this.getNextAction2()
            }
            this.$refs.form.validate(async (valid) => {
                if (valid || data.Status == '2' || data.Status == '3') {//转派和退回时可不校验必填框
                    this.submitLoading = true;
                    //异常类型变成id的格式
                    data.AbnormalTypeId = data.AbnormalTypeId[data.AbnormalTypeId.length - 1]
                    if (data.TreatmentAttachments) {
                        data.TreatmentAttachments = this.removeUrlPrefix(data.TreatmentAttachments)
                        data.TreatmentAttachments = this.jsonToString(data.TreatmentAttachments)
                    }
                    data.InitiatorAttachments = this.removeUrlPrefix(data.InitiatorAttachments)
                    data.InitiatorAttachments = this.jsonToString(data.InitiatorAttachments)
                    data.EquipmentCodes = this.jsonToString(data.EquipmentCodes)
                    data.isUpdate = this.status == 1
                    this.http.post('/api/Ads_Task/AddOrUpdate', data).then(r => {
                        this.$emit('success'); // 触发自定义事件
                        this.editFormVisible = false
                        this.$message.success("保存成功")
                        console.log('请求结果', r)
                    }).catch(error => {
                        console.log('请求失败', error)
                    }).finally(() => {
                        this.submitLoading = false;
                    });
                } else {
                    this.$message.warning('请填写完整表单');
                }
            });
        },
        cascaderChange(value,Priority) {
            if (value?.length > 0) {
                this.http.get('/api/Ads_AbnormalType/GetDetail', { AbnormalTypeId: value[value.length - 1] })
                    .then(response => {
                        if (response) {
                            this.abnormalType.depts = response.ResponsibleDept ? JSON.parse(response.ResponsibleDept) : []
                            this.abnormalType.persons = response.ResponsiblePersons ? JSON.parse(response.ResponsiblePersons) : []
                            if(Priority!==undefined){
                                this.formData.Priority = String(Priority)
                            }else{
                                this.formData.Priority = String(response.Priority)
                            }
                        }
                    })
                    .catch(error => {
                        console.error('获取异常类型详情数据失败:', error);
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            }
        },
        //上传图片
        uploadFile(position) {
            var file = position.file
            var forms = new FormData();
            forms.append('fileInput', file);
            // 发起 POST 请求
            this.http
                .post('/api/Ads_Task/upload', forms, true, { headers: { 'Content-Type': 'multipart/form-data' } })
                .then((x) => {
                    // 根据返回的路径更新
                    this.formData.InitiatorAttachments.push({ "name": file.name, "url": x + file.name });
                    this.formData.InitiatorAttachments = this.addUrlPrefix(this.formData.InitiatorAttachments)
                })
                .catch((error) => {
                    console.error('File upload failed:', error);
                });
        },
        uploadTreatmentFile(position) {
            var file = position.file
            var forms = new FormData();
            forms.append('fileInput', file);
            // 发起 POST 请求
            this.http
                .post('/api/Ads_Task/upload', forms, true, { headers: { 'Content-Type': 'multipart/form-data' } })
                .then((x) => {
                    // 根据返回的路径更新
                    this.formData.TreatmentAttachments.push({ "name": file.name, "url": x + file.name });
                    this.formData.TreatmentAttachments = this.addUrlPrefix(this.formData.TreatmentAttachments)
                })
                .catch((error) => {
                    console.error('File upload failed:', error);
                });
        },
        //移除图片
        removePic(UploadFile) {
            this.formData.InitiatorAttachments = this.formData.InitiatorAttachments.filter((file) => file.name !== UploadFile.name)
        },
        //移除处理图片
        removeTreatmentPic(UploadFile) {
            this.formData.TreatmentAttachments = this.formData.TreatmentAttachments.filter((file) => file.name !== UploadFile.name)
        },
        handleClick(tab, event) {
            if (this.logList.length > 0) {
                return
            }
            if (tab.props.name == 'second' && this.formData.TaskId) {
                this.http.get('/api/Ads_Task/GetTaskLog', { TaskId: this.formData.TaskId }, {})
                    .then(response => {
                        console.log(response)
                        this.logList = response
                    })
                    .catch(error => {
                        console.error('获取异常类型数据失败:', error);
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            }
        },
        //展示图片
        handlePictureCardPreview(uploadFile) {
            this.dialogImageUrl = uploadFile.url
            this.dialogVisible = true
            this.dialogTitle = uploadFile.name
        },
        // 关闭弹框
        handleClose() {
            this.$refs.form.resetFields();
            this.editFormVisible = false
        },
        addUrlPrefix(fileList) {
            if (fileList != null) {
                return fileList.map(file => {
                    // 如果 aa 已经有前缀，避免重复添加
                    if (!file.url.startsWith(url)) {
                        file.url = url + file.url;
                    }
                    return file;
                });
            } else {
                return []
            }
        },
        removeUrlPrefix(fileList) {
            return fileList.map(file => {
                return {
                    name: file.name,
                    url: file.url.replace(url, '')
                };
            });
        },
        stringToJson(str) {
            try {
                if (str == null || str == undefined) {
                    return []
                }
                return JSON.parse(str);
            } catch (error) {
                return [];
            }
        },
        jsonToString(json) {
            try {
                return JSON.stringify(json);
            } catch (error) {
                return '';
            }
        },
        findParentIds(data, targetId, path = []) {
            for (let item of data) {
                // 如果当前节点的 ID 匹配目标 ID
                if (item.value === targetId) {
                    return [...path, item.value]; // 返回路径
                }
                // 如果当前节点有子节点，递归查找
                if (item.children && item.children.length > 0) {
                    const result = this.findParentIds(item.children, targetId, [...path, item.value]);
                    if (result) {
                        return result; // 如果找到目标，返回路径
                    }
                }
            }
            return null; // 如果未找到目标，返回 null
        },
        refreshCascader() {
            this.cascaderKey += 1; // 修改 key 值，强制刷新组件
        },
        fetchTreeData() {
            this.loading = true;
            this.http.get('/api/Ads_AbnormalType/GetTree', null, {})
                .then(response => {
                    console.log(response)
                    if (response.length > 0) {
                        this.treeData = this.transformTreeData(response);
                    } else {
                        this.selectedNode = true
                        this.tabName = '新增'
                    }
                })
                .catch(error => {
                    console.error('获取异常类型数据失败:', error);
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        transformTreeData(items) {
            return items.map(item => ({
                parentId: item.ParentId,
                id: item.AbnormalTypeId,
                label: `${item.AbnormalCode} - ${item.AbnormalName}`,
                children: item.Children ? this.transformTreeData(item.Children) : [],
                rawData: item
            }));
        },
        transformData(data) {
            const map = new Map();
            const result = [];

            data.forEach(item => {
                map.set(item.id, { ...item, children: [] });
            });

            data.forEach(item => {
                if (item.parentId === null) {
                    result.push(map.get(item.id));
                } else {
                    const parent = map.get(item.parentId);
                    if (parent) {
                        parent.children.push(map.get(item.id));
                    }
                }
            });

            const mapToCascaderFormat = (node) => {
                return {
                    label: node.value,
                    value: node.id,
                    children: node.children.length > 0 ? node.children.map(mapToCascaderFormat) : undefined,
                };
            };

            return result.map(mapToCascaderFormat);
        },
    },
    created() {
    },
};
</script>

<style lang="scss" scoped>
::v-deep .el-tabs__header.is-top {
    border-left: 1px solid #fff !important;
}

.timeline-container {
    height: 485px;
    overflow-y: auto;
    border: 1px solid #ebeef5;
    padding: 10px;
    border-radius: 4px;
}

.dialog-footer {
    text-align: right;
}

/* 表单容器 */
.form-container {
    display: flex;
    justify-content: flex-start;
}

/* 默认情况下，左侧表单占满宽度 */
.left-form {
    width: 50%;
}

.right-form {
    width: 50%;
}

/* 当 status === 2 时，左右表单均匀分布 */
.form-container.two-columns .left-form {
    width: 50%;
    /* 左侧表单宽度 */
}

.form-container.two-columns .right-form {
    width: 50%;
    /* 右侧表单宽度 */
}

/* 图片容器样式 */
.image-container {
    justify-content: center;
    align-items: center;
    max-height: 80vh;
    /* 限制最大高度为视口的 80% */
    overflow: auto;
    /* 如果图片过大，允许滚动 */
}

/* 图片自适应样式 */
.responsive-image {
    max-width: 100%;
    /* 图片最大宽度为容器宽度 */
    max-height: 100%;
    /* 图片最大高度为容器高度 */
    object-fit: contain;
    /* 保持图片宽高比 */
    border-radius: 4px;
    /* 可选：圆角效果 */
}
</style>